|
|
|
|
|
|
|
If L = 0 Then Exit Function
LocalVar = L
B = B(LocalVar - 1)
End Function
Sub Main()
Call B(1)
End Sub |
|
|
|
|
|
|
|
|
Figure T4-4a shows the stack immediately after Function B() is called for the first time. The parameters are placed on the stack first, then the return address, followed by a value called BP, and finally the local variables. This raises a new question: What is the BP value? BP stands for "base pointer." The base pointer is a register in the CPU that is used to help a function keep track of where parameters and local variables can be found on the stack. When a function begins to execute, the function pushes the existing value of the BP register onto the stack so that the register can be restored on exit. The function then loads the BP register with the current value of the stack pointer and pushes local variables onto the stack. The function can now refer to local variables as offsets to the BP register. In this example, the location of variable LocalVar can be obtained by subtracting 4 from the contents of the BP register. Local variables are above the BP register on the stack; parameters are below it. |
|
|
|
|
|
|
|
|
Figure T4-4b shows the state of the stack after Function B() is called for the second time. As you can see, each time the function is called, it creates its own private copy of the local variable LocalVar. Every time a function is called, it can access its parameters, its local variables, and the return address. The segment of the stack that is used during a particular function call is called a stack frame. |
|
|
|
|
|
|
|
|
You may be wondering why the BP value is pushed onto the stack only when local variables are used. The answer is simple: I lied earlier. The BP value is always pushed onto the stackunless the compiler is smart enough to detect that it isn't used and skips that step. You see, the intent of this section is not to turn you into an expert on the intricacies of every detail of how stack frames are created and used. As a Visual Basic programmer, you don't need to know that. The key points you need to remember are these: |
|
|
|
|
|